<template>
  <div class="app-container">
    <el-card>
      <el-form :model="searchForm" inline size="small">
        <el-form-item label="地区名称">
          <el-input v-model="searchForm.name" placeholder="请输入地区名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="查询时间：" prop="beginTime">
          <el-date-picker style="width: 200px" v-model="searchForm.beginTime" align="right" type="date"
            placeholder="选择开始日期" :picker-options="$pickerDateOptions" value-format="yyyy-MM-dd"
            format="yyyy 年 MM 月 dd 日">
          </el-date-picker>
        </el-form-item>
        <el-form-item>-</el-form-item>
        <el-form-item prop="endTime">
          <el-date-picker style="width: 200px" v-model="searchForm.endTime" align="right" type="date"
            placeholder="选择结束日期" :picker-options="$pickerDateOptions" value-format="yyyy-MM-dd"
            format="yyyy 年 MM 月 dd 日">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" @click="reset()">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="handleSearchList">查询</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button size="mini" icon="el-icon-plus" type="primary" @click="addregoin()">添加地区</el-button>
        <el-button size="mini" icon="el-icon-edit" type="primary" @click="batchEdit">批量编辑</el-button>
        <el-button size="mini" icon="el-icon-delete" @click="deletebatchRegion">批量删除</el-button>
      </div>
      <el-table :data="tableData.data" border size="small" style="width: 100%; margin-top: 20px"
        @selection-change="handleSelectionChange" :loading="listLoading">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="地区名称" align="center">
        </el-table-column>
        <el-table-column prop="pinyin" label="地区拼音" align="center">
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag size="small" :type="scope.row.status == 1 ? 'success' : 'danger'">{{ scope.row.status == 1 ? "启用" :
              "禁用" }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="税务状态" align="center">
          <template slot-scope="scope">
            <el-tag size="small" :type="scope.row.taxStatus == 1 ? 'success' : 'danger'">{{ scope.row.taxStatus == 1 ?
              "启用" : "禁用" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发票状态" align="center">
          <template slot-scope="scope">
            <el-tag size="small" :type="scope.row.invoiceStatus == 1 ? 'success' : 'danger'">{{ scope.row.invoiceStatus
              == 1 ? "启用" : "禁用" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="维护起止时间" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.startTime && scope.row.endTime" :style="{
              color:
                scope.row.taxStatus == 0 || scope.row.invoiceStatus == 0
                  ? 'red'
                  : ''
            }">
              {{
                scope.row.taxStatus == 0 || scope.row.invoiceStatus == 0
                  ? `${scope.row.startTime} - ${scope.row.endTime} `
                  : "-"
              }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template slot-scope="scope">{{ scope.row.createTime }}</template>
        </el-table-column>
        <el-table-column label="更新时间" align="center">
          <template slot-scope="scope">{{ scope.row.updateTime }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="editregoin(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="deleteregoin(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pageRight" background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40]" :current-page="searchForm.pageNum" :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="tableData.total">
      </el-pagination>

      <!--      :title="detailForm.id ? '编辑地区' : '新增地区'"-->
      <el-dialog :title="`${batchEditable
          ? '批量编辑'
          : `${detailForm.id ? '编辑地区' : '新增地区'}`
        }`
        " :visible.sync="dialogVisible" width="700px" :before-close="handleClose">
        <el-form :model="detailForm" :rules="detailRules" ref="detailForm" label-width="120px" size="small">
          <el-form-item v-if="!batchEditable" label="地区名称：" prop="name">
            <el-input style="width: 500px" v-model="detailForm.name"></el-input>
          </el-form-item>
          <el-form-item v-if="!batchEditable" label="地区拼音：" prop="pinyin">
            <el-input style="width: 500px" v-model="detailForm.pinyin"></el-input>
          </el-form-item>

          <el-form-item label="状态：" prop="status">
            <el-radio-group style="width: 500px" v-model="detailForm.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="发票状态：" prop="invoiceStatus">
            <el-radio-group style="width: 500px" v-model="detailForm.invoiceStatus">
              <el-radio label="1">正常</el-radio>
              <el-radio label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="税务状态：" prop="taxStatus">
            <el-radio-group style="width: 500px" v-model="detailForm.taxStatus">
              <el-radio label="1">正常</el-radio>
              <el-radio label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="税务时间起止：" v-if="
            detailForm.taxStatus == '0' || detailForm.invoiceStatus == '0'
          ">
            <!-- <el-date-picker
              style="width: 500px"
              v-model="detailForm.addFormTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy 年 MM 月 dd 日 HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker> -->
            <el-date-picker v-model="detailForm.addFormTime" type="datetimerange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>

          <el-form-item label-width="30px">
            <div>
              <el-button v-if="!batchEditable" style="width: 100px" type="primary"
                @click="onSubmit('detailForm')">确定</el-button>
              <el-button v-if="batchEditable" style="width: 100px" type="primary"
                @click="batchSubmit('detailForm')">确定</el-button>
              <el-button style="width: 100px" @click="handleClose()">取消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import {
  getRegionList,
  addRegion,
  editRegion,
  deleteRegion,
  deletebatchRegion
} from "@/api/system/region";

export default {
  name: "index",
  watch: {
    "detailForm.addFormTime": {
      handler(val) {
        if (val) {
          this.detailForm.startTime = val[0];
          this.detailForm.endTime = val[1];
        } else {
          this.detailForm.startTime = "";
        }
      }
    }
  },
  data() {
    return {
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        name: "",
        status: "", //启用状态：0->禁用；1->启用
        beginTime: "",
        endTime: ""
      },
      tableData: {
        data: [],
        total: 0
      },
      listLoading: false,
      searchTime: [],
      dialogVisible: false,
      detailForm: {
        name: "",
        pinyin: "",
        status: 1, //启用状态：0->禁用；1->启用
        invoiceStatus: "1", //发票信息 1 正常使用 0 维护中
        taxStatus: "1", //税务信息状态 1 正常使用 0 维护中',
        startTime: "",
        endTime: "",
        addFormTime: []
      },
      detailRules: {
        name: [{ required: true, message: "请输入地区名称", trigger: "blur" }],
        pinyin: [
          { required: true, message: "请输入地区拼音", trigger: "blur" }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
        invoiceStatus: [
          { required: true, message: "请选择发票状态", trigger: "blur" }
        ],
        taxStatus: [
          { required: true, message: "请选择税务状态", trigger: "blur" }
        ],
        addFormTime: [
          { required: true, message: "请选择起止时间", trigger: "blur" }
        ]
      },
      pickerOptions: {
        disabledDate: time => {
          return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
        }
      },
      selectList: [],
      batchEditable: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
     handleSearchList() {
      this.searchForm.pageNum = 1;
      this.$authDate(this.searchForm.beginTime, this.searchForm.endTime, v => {
        if (!v.type) {
          return this.$message.warning(v.msg);
        } else {
          // console.log(this.searchForm);
          this.getList();
        }
      });
    },
    batchEdit() {
      if (this.selectList.length === 0) {
        return this.$message({
          message: "请选择要编辑的数据",
          type: "warning"
        });
      } else {
        this.batchEditable = true;
        this.dialogVisible = true;
      }
    },
    reset() {
      this.searchForm = {
        pageNum: 1,
        pageSize: 10,
        name: "",
        status: "", //启用状态：0->禁用；1->启用
        beginTime: "",
        endTime: ""
      };
      this.searchTime = [];
      this.getList();
    },
    editregoin(row) {
      let obj = Object.assign({}, row);
      if (obj.startTime && obj.endTime) {
        obj.addFormTime = [obj.startTime, obj.endTime];
      } else {
        obj.addFormTime = [];
      }
      // obj.addFormTime =
      //   obj.startTime && obj.endTime ? [obj.startTime, obj.endTime] : [];
      this.detailForm = obj;
      this.dialogVisible = true;
    },
    batchSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const obj = Object.assign({}, this.detailForm);
          if (this.detailForm.addFormTime) {
            obj.startTime = this.detailForm.addFormTime[0];
            obj.endTime = this.detailForm.addFormTime[1];
          }

          delete obj.addFormTime;

          delete obj.name;
          delete obj.pinyin;
          obj.ids = this.selectList;
          console.log(obj);
          editRegion(obj).then(res => {
            this.$message({
              message: "修改成功",
              type: "success"
            });
            this.ressetDetailForm();
            this.getList();
          });
        }
      });
    },
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const obj = Object.assign({}, this.detailForm);
          // if (
          //   this.detailForm.taxStatus == 0 ||
          //   this.detailForm.invoiceStatus == 0
          // ) {
          //   obj.startTime = this.detailForm.addFormTime[0];
          //   obj.endTime = this.detailForm.addFormTime[1];
          // delete obj.addFormTime;
          // }
          delete obj.addFormTime;
          if (obj.id) {
            delete obj.createTime;
            delete obj.updateTime;
            editRegion(obj).then(res => {
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.ressetDetailForm();
              this.getList();
            });
          } else {
            addRegion(obj).then(res => {
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.ressetDetailForm();
              this.getList();
            });
          }
          //   console.log("this.detailForm", this.detailForm);
        }
      });
    },
    ressetDetailForm() {
      this.dialogVisible = false;
      this.$refs.detailForm.clearValidate();

      setTimeout(() => {
        this.detailForm = {
          name: "",
          pinyin: "",
          status: 1, //启用状态：0->禁用；1->启用
          invoiceStatus: "1", //发票信息 1 正常使用 0 维护中
          taxStatus: "1", //税务信息状态 1 正常使用 0 维护中',
          startTime: "",
          endTime: ""
        };
      }, 100);
    },
    handleClose() {
      this.batchEditable = false;
      this.ressetDetailForm();
    },
    addregoin() {
      this.dialogVisible = true;
    },
    handleSelectionChange(v) {
      this.selectList = v.map(v => v.id);
    },
    deleteregoin(row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteRegion(row.id).then(res => {
          this.$message({
            message: "删除成功",
            type: "success"
          });
          this.getList();
        });
      });
    },
    deletebatchRegion() {
      if (this.selectList.length == 0) {
        this.$message({
          message: "请选择要删除的数据",
          type: "warning"
        });
      } else {
        this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          deletebatchRegion(this.selectList).then(res => {
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.getList();
          });
        });
      }
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.searchForm.pageNum = val;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      getRegionList(this.searchForm)
        .then(res => {
          this.tableData.data = res.data.list;
          this.tableData.total = res.data.total;
          this.listLoading = false;
        })
        .finally(() => {
          this.listLoading = false;
        });
    }
  }
};
</script>
<style lang="scss" scoped></style>
